package com.cloudfunx.filter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.datasource.embedded.DataSourceFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.sound.sampled.Line;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.SQLException;
import java.util.List;
import java.util.Objects;

/**
 * @author linjiayu
 */
@Configuration
@ConfigurationProperties(prefix = "reqlog")
public class ReqlogMvcConfiguration implements WebMvcConfigurer {
    @Autowired(required = false)
    private JdbcInfo jdbcInfo;
    private List<String> excludePathPatterns;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration interceptorRegistration = registry.addInterceptor(new ReqlogInterceptor());
        if (!CollectionUtils.isEmpty(excludePathPatterns)) {
            interceptorRegistration.excludePathPatterns(this.excludePathPatterns);
        }
        interceptorRegistration.addPathPatterns("/**");
        System.out.println("req-log interceptors init");
        if (Objects.nonNull(jdbcInfo)) {
            DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource(jdbcInfo.getUrl(), jdbcInfo.getUser(), jdbcInfo.getPassword());
            driverManagerDataSource.setDriverClassName(jdbcInfo.getDriverClassName());
            JdbcTemplate jdbcTemplate = new JdbcTemplate(driverManagerDataSource);

            ReqlogContext.ofJdbcTemplate(jdbcTemplate);
            System.out.println("init dataSource");
        }
    }

    public List<String> getExcludePathPatterns() {
        return excludePathPatterns;
    }

    public void setExcludePathPatterns(List<String> excludePathPatterns) {
        this.excludePathPatterns = excludePathPatterns;
    }
}
